#encoding=utf-8
'''
Created on 2011-12-7

@author: sunny
'''

grammars=[]

def ReadData(filename):
    infile=open(filename,'r')
    lines=infile.readlines()
    infile.close()
    return lines

def IsTerminal(checktag,untags):
    for tag in untags:
        if checktag==tag:
            return False
    return True

def CountUnTags(filename):
    lines=ReadData(filename)
    out=open("Data//unTags.txt",'w')
    for line in lines:
        line=line.strip()
        tags=line.split(" ")
        out.write(tags[0]+"\n")
    out.close()
        

def AllTags(filename):
    CountUnTags(filename)
    lines=ReadData("Data//unTags.txt")
    lis=[]
    for line in lines:
        line=line.strip()
        tags=line.split("  ")
        for tag in tags:
            lis.append(tag)
    return list(set(lis))

def SaveTerminal(lis,alltags):
    li=[]
    for tag in lis:
        if IsTerminal(tag,alltags):
            li.append(tag)
    return li

def IsOver(dict1,alltags):
    for item in dict1.items():
        for tag in item[1]:
            if not IsTerminal(tag,alltags):
                return False
    return True

def DealOne(dict1,alltags,dic):
    for item in dict1.items():
        #li=item[1]
        li=list(set(item[1]))
        for i in range(len(li)):
            if not IsTerminal(li[i],alltags):
                if(dic.has_key(li[i])and len(dic[li[i]])>0):
                    for gra in dic[li[i]]:
                        grammars.append(item[0]+" -> "+gra[0]+" "+gra[1]+"\n")
                        #result.write(item[0]+" → "+gra[0]+" "+gra[1]+"\n")
                if(not dict1.has_key(li[i])):
                    dict1[item[0]].remove(li[i])
                    i-=1
                    continue
                dict1[item[0]]+=dict1[li[i]]
                dict1[item[0]].remove(li[i])
                i-=1
    if IsOver(dict1,alltags):
        print("DealOne over")
        for item in dict1.items():
            ta=list(set(item[1]))
            for tag in ta:
                grammars.append(item[0]+" -> "+tag+"\n")
        #print grammars2
        return
    else:
        DealOne(dict1,alltags,dic)

def SingleTerminal(tag0,tag,alltags):
    if(IsTerminal(tag,alltags)):
        s="_"+tag
        grammars.append(s+" -> "+tag+"\n")
        tag=s
    return tag
    
def ToChomsky(lines,filename):
    alltags=AllTags(filename)
    for line in lines:
        line=line.strip()
        tags=line.split(" ")
        #print tags
        if(len(tags)==4):
            for x in range(2,4):
                tags[x]=SingleTerminal(tags[0],tags[x],alltags)
            #result.write(tags[0]+" → "+tags[2]+" "+tags[3]+"\n")
            grammars.append(tags[0]+" -> "+tags[2]+" "+tags[3]+"\n")
        elif(len(tags)==3):
            continue
        elif(len(tags)==5):
            for x in range(2,5):
                tags[x]=SingleTerminal(tags[0],tags[x],alltags)
            grammars.append(tags[0]+" -> "+tags[2]+" "+tags[3]+" "+tags[4]+"\n")
        else:
            print("abnormal")
            print tags
            #grammars.append(tags)
    return
    #print grammars
    #print grammars2
    #return grammars+grammars2


def WriteGrammars(filename):
    ToChomsky(ReadData(filename),filename)
    li=list(set(grammars))
    li.sort()
    print "start write file"
    result=open("Data//ChomskyRule.txt",'w')
    for grammar in li:
        result.write(grammar)
    result.close()

if __name__ == '__main__':
    WriteGrammars("Data//Rule.txt")
    #print ToChomsky(ReadData("Data//Rule.txt"))
    print ("over" )